package com.cxg.fairy.ec.main.personal.profile;


import com.alibaba.fastjson.JSON;
import com.cxg.fairy.util.toasty.Toasty;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by CFairy on 2017/11/2
 */

public final class RestUploadClient {

    private static final WeakHashMap<String, Object> PARAMS = new WeakHashMap<>();

    private String key = null;
    private String value = null;
    public String headIco = "";

    public void process_formdata_file(String filename, String filePath, String urlStr, WeakHashMap PARAMS, final UserProfileDelegate DELEGATE) {

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        File FILE = new File(filePath);

        builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + filename + "\";filename=\"" + FILE.getName() + "\""),
                RequestBody.create(MediaType.parse("application/octet-stream"), FILE)).build();

        Iterator iter = PARAMS.entrySet().iterator();
        while(iter.hasNext()) {
            Map.Entry entry = (Map.Entry)iter.next();
            key = (String)entry.getKey();
            value = entry.getValue().toString();
            builder.addFormDataPart(key, value);
        }

        RequestBody body = builder.build();

        Request request = new Request.Builder().url(urlStr).post(body).build();

        // 创建/Call
        OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).build();
        Call calls = okHttpClient.newCall(request);
        // 加入队列 异步操作
        calls.enqueue(new Callback() {
            // 请求错误回调方法
            @Override
            public void onFailure(Call call, IOException e) {
                Toasty.error(DELEGATE.getContext(), "上传头像失败!").show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                int code = JSON.parseObject(res).getInteger("code");
                if (code == 1) {
                    Toasty.success(DELEGATE.getContext(), "上传头像成功!").show();
                } else {
                    Toasty.error(DELEGATE.getContext(), "上传头像失败!").show();
                }
                response.body().close();
            }
        });
    }
}
